var PurchaseMaterialForm = function () {
  var PurchaseMaterialItem = function () {
    var template = /* html */ `
      <div class="purchase-material-item">
        <div class="purchase-material-info clearfix">
          <div>
            <span>供应商:</span>
            <table-dealer-select v-model="material.provider" style="width:220px" :order="material" :dealer-list="dealerList" :dealer-obj="dealerObj">
            </table-dealer-select>
          </div>
          <div>
            采购员:{{material.purchasePeople}}
          </div>
        </div>
        <div>
          <el-table fit stripe border show-summary :data="material.materials" style="width: 100%" :summary-method="summaryMethod">
            <el-table-column prop="materialName" label="物料名称" min-width="120px" header-align="center">
            </el-table-column>
            <el-table-column prop="model" label="规格型号" min-width="100px" header-align="center">
            </el-table-column>
            <el-table-column prop="color" label="编号" min-width="90px" header-align="center">
            </el-table-column>
            <el-table-column prop="colorDescription" label="描述" min-width="100px" header-align="center">
            </el-table-column>
            <el-table-column prop="materialDeptName" label="物料部门" min-width="100px" align="center">
            </el-table-column>
            <el-table-column prop="unit" label="单位" min-width="60px" align="center">
            </el-table-column>
            <el-table-column :label="getTaxLabel(material)" min-width="100px" header-align="center">
              <template slot-scope="scope">
                <el-input-number is-decimal-zero size="mini" class="table-input" v-model="scope.row.unitPrice" :controls="false" :min="0" :precision="4"
                  :after-change-format-value="checkNumber"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="defaultWarehouse" label="仓库" min-width="80px" align="center">
            </el-table-column>
            <el-table-column label="税率(%)" prop="tax" min-width="80px" header-align="center">
              <template slot-scope="scope">
                <el-input-number size="mini" v-if="material.provider.isTax" class="table-input" v-model="scope.row.tax" :controls="false" :min="1" :max="100"
                  :precision="2" :after-change-format-value="checkNumber"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="采购数量" prop="countPrecision" min-width="140px" header-align="center">
              <template slot-scope="scope">
                <el-input-number is-decimal-zero size="mini" class="table-input" v-model="scope.row.purchaseCount" :controls="false"
                  :precision="scope.row.countPrecision" :min="0" :after-change-format-value="checkNumber">
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="含税金额" prop="totalMoney" min-width="100px" align="center">
              <template slot-scope="scope">
                {{getTotalMoney(scope.row,globalConfig.pricePrecision)}}
              </template>
            </el-table-column>
            <el-table-column label="税额" prop="taxMoney" min-width="100px" align="center">
              <template slot-scope="scope">
                {{getTotalTaxMoney(scope.row,globalConfig.pricePrecision)}}
              </template>
            </el-table-column>
            <el-table-column label="备注" prop="remark" min-width="180px" header-align="center">
              <template slot-scope="scope">
                <el-input size="mini" v-model="scope.row.remark"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    `;

    return {
      props: {
        material: {
          type: Object,
          required: true
        },
        user: {
          type: Object,
          required: true
        },
        dealerList: {
          type: Array,
          default: function () {
            return [];
          }
        },
        dealerObj: {
          type: Object,
          default: function () {
            return {};
          }
        }
      },

      data: function () {
        return {};
      },

      methods: {
        getTaxLabel: function (material) {
          var isTax = material.provider.isTax;
          return isTax ? '含税单价' : '单价';
        },

        getTotalMoney: function (material, precision) {
          var purchaseCount = material.purchaseCount;
          if (SysUtil.isEmpty(purchaseCount)) {
            return 0;
          }

          var unitPrice = material.unitPrice;
          if (SysUtil.isEmpty(unitPrice)) {
            return 0;
          }
          var total = purchaseCount * unitPrice;
          if (precision !== undefined) {
            total = _.round(total, precision);
          }
          return total;
        },

        getTotalTaxMoney: function (material, precision) {
          var tax = material.tax;
          if (SysUtil.isEmpty(tax)) {
            return 0;
          }

          var total = this.getTotalMoney(material);
          total = total * (tax / 100);
          if (precision !== undefined) {
            total = _.round(total, precision);
          }
          return total;
        },

        checkNumber: function (value) {
          return value !== undefined;
        },

        summaryMethod: function (param) {
          var columns = param.columns;
          var data = param.data;
          var sums = ['合计'];
          var self = this;
          for (var i = 1; i < columns.length; i++) {
            var column = columns[i];
            var columnKey = column.columnKey;
            if (columnKey !== 'totalMoney') {
              sums.push(null);
              continue;
            }
            var sumData = _.sumBy(data, function (obj) {
              var value = self.getTotalMoney(obj, globalConfig.pricePrecision);
              return value;
            });
            sums.push(sumData);
          }
          return sums;
        }
      },

      components: {
        TableDealerSelect: TableDealerSelect
      },

      template: template
    };
  }();

  var template = /* html */ `
    <div class="purchase-material-form" v-loading.fullscreen.lock="loading">
      <div class="handle-btn" style="margin-bottom:10px;">
        <el-button type="primary" size="medium" @click="purchaise(false)">采购</el-button>
        <el-button type="primary" size="medium" @click="purchaise(true)" :disabled="!hasApproval">审核过账</el-button>
        <span style="margin-left:20px" v-if="sumMomeny!==''">含税金额总计:{{sumMomeny}}</span>
      </div>
      <div class="order-info">
        <el-form :inline="true" size="small">
          <el-form-item label="订单编号">
            <el-input class="order-input" v-model="orderInfo.customerOrderId"></el-input>
          </el-form-item>
          <el-form-item label="工厂型号">
            <el-input class="order-input" v-model="orderInfo.factoryId"></el-input>
          </el-form-item>
          <el-form-item label="客户型号">
            <el-input class="order-input" v-model="orderInfo.customerId"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div v-if="materialList!==null">
        <purchase-material-item v-for="material in materialList" :key="material.id" :material="material" :dealer-list="dealerList"
          :dealer-obj="allDealerObj">
        </purchase-material-item>
      </div>
    </div>
  `;

  return {
    props: {
      materials: {
        type: Array,
        required: true
      },
      user: {
        type: Object,
        required: true
      },
      option: {
        type: Object,
        default: function () {
          return {};
        }
      }
    },

    computed: {
      sumMomeny: function () {
        var materialList = this.materialList;
        if (materialList === null) {
          materialList = [];
        }

        var precision = globalConfig.pricePrecision;
        var sumValue = _.sumBy(materialList, function (material) {
          var materials = material.materials;
          if (SysUtil.isEmpty(materials)) {
            return 0;
          }

          var sum = _.sumBy(materials, function (obj) {
            var purchaseCount = obj.purchaseCount;
            if (SysUtil.isEmpty(purchaseCount)) {
              return 0;
            }

            var unitPrice = obj.unitPrice;
            if (SysUtil.isEmpty(unitPrice)) {
              return 0;
            }
            var total = purchaseCount * unitPrice;
            if (precision !== undefined) {
              total = _.round(total, precision);
            }
            return total;
          });
          return sum;
        });
        return sumValue;
      }
    },

    data: function () {
      return {
        loading: false,
        materialList: null,
        dealerList: null,
        hasApproval: false,
        dealerObj: null,
        allDealerObj: null,
        orderInfo: {
          factoryId: '',
          customerOrderId: '',
          customerId: ''
        }
      };
    },

    created: function () {
      this.loading = true;
      var self = this;
      Promise.all([
        this.checkApproval(),
        this.setDealerList()
      ]).then(function () {
        self.loading = false;
        self.materialList = self.getMaterialGroups();
      }).catch(function () {
        self.loading = false;
      });
    },

    methods: {
      setDealerList: function () {
        var self = this;
        return DropdownUtil.getDealerList().then(function (res) {
          self.dealerList = res.dealerList;
          self.dealerObj = res.dealerObj;
          self.allDealerObj = res.allDealerObj;
          return res;
        });
      },

      checkApproval: function () {
        var option = this.option;
        if (option.hasApproval !== undefined) {
          this.hasApproval = option.hasApproval;
          return Promise.resolve(option.hasApproval);
        }

        var self = this;
        return PermissionUtil.ajaxCheckPermission(4).then(function (hasApproval) {
          option.hasApproval = hasApproval;
          self.hasApproval = hasApproval;
          return hasApproval;
        });
      },

      getMaterialGroups: function () {
        var materials = this.materials;
        var materialGroup = _.groupBy(materials, 'providerName');
        var materialList = [];
        var purchasePeople = this.user.userName;
        var purchasePeopleId = this.user.userId;
        var dealerObj = this.dealerObj;
        for (var providerName in materialGroup) {
          var materialDatas = materialGroup[providerName];
          materialDatas = _.cloneDeep(materialDatas);
          var provider;
          if (dealerObj === null) {
            provider = '';
          } else {
            provider = dealerObj[providerName];
            if (SysUtil.isEmpty(provider)) {
              provider = '';
            }
          }

          var otherProviderOption = null;
          if (provider === '') {
            provider = {
              id: 0,
              dataId: '0-1',
              name: providerName,
              source: 1,
              isTax: materialDatas[0].isTax === 0,
            };
            otherProviderOption = _.clone(provider);
          }

          var obj = {
            id: SysUtil.getId(),
            provider: provider,
            otherProviderOption: otherProviderOption,
            purchasePeople: purchasePeople,
            purchasePeopleId: purchasePeopleId,
            currency: '人民币',
            materials: materialDatas
          };
          materialList.push(obj);
        }
        return materialList;
      },

      purchaise: function (isApproval) {
        var purchaseMaterialList = this.materialList;
        var orderInfo = this.orderInfo;
        var purchasePostDataList = [];
        var fields = ['materialCode', 'materialName', 'model', 'color', 'colorDescription', 'tax',
          'purchaseCount', 'procurementCycles', 'remark'
        ];
        var orderInfoFields = ['factoryId', 'customerOrderId', 'customerId'];

        for (var i = 0; i < purchaseMaterialList.length; i++) {
          var purchaseMaterial = purchaseMaterialList[i];
          var materials = purchaseMaterial.materials;
          var materialList = [];
          var provider = purchaseMaterial.provider;
          for (var j = 0; j < materials.length; j++) {
            var material = materials[j];
            var purchaseCount = material.purchaseCount;
            if (purchaseCount === undefined) {
              this.$alert('请输入采购数量', '信息');
              return;
            }

            if (purchaseCount === 0) {
              this.$alert('采购数量不能为0', '信息');
              return;
            }

            var obj = {
              price: material.unitPrice,
            };
            SysUtil.setPostData(obj, material, fields, false, true);
            SysUtil.setPostData(obj, orderInfo, orderInfoFields, false, true);

            if (!provider.isTax) {
              obj.tax = 0;
            }

            materialList.push(obj);
          }

          purchasePostDataList.push({
            purchasePeople: purchaseMaterial.purchasePeopleId,
            providerName: provider.name,
            agent: provider.id,
            agentSource: provider.source,
            currency: purchaseMaterial.currency,
            type: 2,
            status: 0,
            detailList: materialList
          });
        }

        var postData = {
          purchase: JSON.stringify(purchasePostDataList)
        };
        if (isApproval) {
          postData.selfApproval = 1;
        }

        this.loading = true;
        var self = this;
        ajaxRequest('purchaseOrder/savePurchaseStack', postData).then(function () {
          self.$alert('物料采购成功', '信息', {
            callback: function () {
              self.$emit('purchaise-success');
            }
          });
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      }
    },

    components: {
      PurchaseMaterialItem: PurchaseMaterialItem
    },

    template: template
  };
}();
